package com.liuyz.inputstream_;

import com.liuyz.Dog;
import org.junit.Test;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class 对象字节输入流 {

    // 读取文件中的对象
    @Test
    public void read_1() {
        // 存储对象的文件路径（该文件的后缀无所谓，其内容格式是按照对象流的格式保存的）
        String path = "d:\\data.dat";
        ObjectInputStream inputStream = null;
        try {
            // 构建对象字节输入流
            inputStream = new ObjectInputStream(new FileInputStream(path));
            // 读取时需要按写入顺序来读取
            System.out.println(inputStream.readInt());
            System.out.println(inputStream.readBoolean());
            System.out.println(inputStream.readChar());
            System.out.println(inputStream.readDouble());
            System.out.println(inputStream.readUTF());
            Object object = inputStream.readObject();
            // 需要使用该对象的方法时，需要进行向下转型，这也就需要读取类需要有访问该对象的权限
            Dog dog = (Dog) object;
            System.out.println(dog);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
